<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="dataForm" layout="inline" label-align="right">
            <a-form-item label="工单号">
              <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch" v-model="pageData.dutymachineCode"
                                        :filter-option="false" allow-search allow-clear
                                        @focus="focusSel({ 'dutymachineCode': '' })">
                                        <a-option v-for="item in pageData.dropDownList" :value="item">
                                            {{ item }}
                                        </a-option>
                                    </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.dutymachineCode" @press-enter="huiche" />
            </a-form-item>

            <a-form-item label="坯布编号">
              <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch1" v-model="dataForm.greyCode"
                                        :filter-option="false" allow-search allow-clear
                                        @focus="focusSel({ 'greyCode': '' })">
                                        <a-option v-for="item in pageData.dropDownList" :value="item">
                                            {{ item }}
                                        </a-option>
                                    </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dataForm.greyCode"
                @press-enter="huiche" />
            </a-form-item>

            <a-form-item label="坯布名称">
              <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch2" v-model="dataForm.grayName"
                                        :filter-option="false" allow-search allow-clear
                                        @focus="focusSel({ 'grayName': '' })">
                                        <a-option v-for="item in pageData.dropDownList" :value="item">
                                            {{ item }}
                                        </a-option>
                                    </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dataForm.grayName"
                @press-enter="huiche" />
            </a-form-item>

            <a-form-item label="织布单号">
              <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch3" v-model="dataForm.planOrderCode"
                                        :filter-option="false" allow-search allow-clear
                                        @focus="focusSel({ 'planOrderCode': '' })">
                                        <a-option v-for="item in pageData.dropDownList" :value="item">
                                            {{ item }}
                                        </a-option>
                                    </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="dataForm.planOrderCode" @press-enter="huiche" />
            </a-form-item>

            <a-form-item label="生产单号">
              <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch4" v-model="dataForm.weaveCode"
                                        :filter-option="false" allow-search allow-clear
                                        @focus="focusSel({ 'weaveCode': '' })">
                                        <a-option v-for="item in pageData.dropDownList" :value="item">
                                            {{ item }}
                                        </a-option>
                                    </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="dataForm.weaveCode" @press-enter="huiche" />
            </a-form-item>

            <a-form-item label-col-flex="52px" label="楼层">
              <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearch5" v-model="dataForm.storey"
                                        :filter-option="false" allow-search allow-clear @focus="focusSel({ 'storey': '' })">
                                        <a-option v-for="item in pageData.dropDownList" :value="item">
                                            {{ item }}
                                        </a-option>
                                    </a-select> -->
              <a-input allow-clear :style="{ width: '214px' }" class="bacClass" placeholder="" v-model="dataForm.storey"
                @press-enter="huiche" />
            </a-form-item>

            <a-form-item label="开始日期">
              <a-date-picker  popup-container="html"  :style="{ width: '200px' }" class="bacClass" v-model="pageData.dateStart"
                @press-enter="huiche" />
            </a-form-item>

            <a-form-item label="结束日期">
              <a-date-picker  popup-container="html"  :style="{ width: '200px' }" class="bacClass" v-model="pageData.dateEnd"
                @press-enter="huiche" />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>

      <!-- <div style="padding: 10px; box-sizing: border-box;position: relative;">
                  
                </div> -->
    </template>
    <template #pageTabel>
      <a-space style="float: right; margin-right: -20px; z-index: 100">
        <div class="my-tool-bar" style="text-align: right; margin-bottom: -40px; z-index: 100">
          <a-button type="primary" size="small" @click="selectHandler"
            style="margin-right: 10px; z-index: 100; cursor: pointer" v-if="permissionStore.hasPermisson('zjpg.cx')">查询
          </a-button>
          <span v-if="tableId == 1">
            <a-button type="primary" size="small" @click="handleClick" style="cursor: pointer; z-index: 100"
              v-if="permissionStore.hasPermisson('zjpg.pg') && pageData.dutymachineState == 0">派工
            </a-button>
          </span>
        </div>
      </a-space>
      <!-- <div class="my-tool-bar" style="margin-right: 10px;margin-bottom: -40px;">
                    <a-button size="mini" style=" margin:5px; " type="primary">中控未审核</a-button>
                    <a-button size="mini" style="margin: 5px;" type="primary">称料</a-button>
                    <a-button size="mini" style="margin: 5px; " type="primary">深色</a-button>
                </div> -->
      <a-tabs   :lazy-load="true" :justify="true" @change="changeTabs" :default-active-key="pageData1.tableIndex">
        <a-tab-pane title="未值机" key="1">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
              <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%" :defaultColDef="defaultColDef"
              class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc1" :localeText="localeText1">
            </AgGridVuesCopys>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane title="已值机" key="2">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
              <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady2" style="height: 100%"
              :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc2"
              :localeText="localeText1">
            </AgGridVuesCopys>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </template>
    <paginationCopys v-if="pageData.dutymachineState == 0" :total="pagination.total" show-total show-jumper show-page-size
      :page-size="pagination.pageSize" :current="pagination.page" @change="PageSize" @page-size-change="change1"
      style="justify-content: center" :page-size-options="pagingList1" />
    <paginationCopys v-else :total="paginations.total" show-total show-jumper show-page-size
      :page-size="paginations.pageSize" :current="paginations.page" @change="PageSize" @page-size-change="change1"
      style="justify-content: center" :page-size-options="pagingList1" />
    <a-drawer style="z-index:999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false"
      :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <template #footer>
                <a-button @click="pageData.showAdd = false">
                    关闭
                </a-button>
                <a-button type="primary" @click="sideOk" v-if="!pageData.isDetails">
                    保存
                </a-button>
            </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="pageData">
          <div v-for="(item, index) in pageData.editYgTime" :key="index">
            <div style="width: 100%">
              <span style="margin-right: 20px">员工名称</span>
              <div style="margin-bottom: 10px; display: inline-block; width: 250px">
                <a-input v-model="item['employeeName']" disabled style="width: 100%" />
              </div><br />
              <span style="margin-right: 20px">开始时间</span>
              <div style="margin-bottom: 10px; display: inline-block; width: 250px">
                <a-date-picker  popup-container="html"  :class="{ 'bacClass': (!pageData.isDetails) }" v-model="item['dutymachineStartDate']" :defaultValue="pageData.NowDate" :disabled="pageData.isDetails"
                  style="width: 100%" />
              </div><br />
              <span style="margin-right: 20px">完成时间</span>
              <div style="margin-bottom: 10px; display: inline-block; width: 250px">
                <a-date-picker  popup-container="html"  :class="{ 'bacClass': (!pageData.isDetails) }" v-model="item['dutymachineEndDate']" :defaultValue="pageData.NowDate" :disabled="pageData.isDetails"
                  style="width: 100%" />
              </div>
            </div>
          </div>
        </a-form>
      </div>
    </a-drawer>
    <a-modal v-model:visible="visible" title="值机派工" @cancel="handleCancel" :draggable="true" width="1200px"
      :ok-loading="pageData.pageLoading" style="z-index: 999">
      <div style="overflow: auto">
        <table id="Table" style="margin: 10px auto">
          <thead>
            <tr>
              <td class="tdStyle">机器</td>
              <td class="tdStyle"></td>
              <td v-for="(item, index) in pageData.checkHeadList" :key="index" class="tdStyle">{{ item }}
              </td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in pageData.checkBodyList" :key="index">
              <td rowspan="2" v-if="item['machineName'] !== ''" class="tdStyle">{{ item['machineName'] }}
              </td>
              <td class="tdStyle">{{ index % 2 == 0 ? '白班' : '晚班' }}</td>
              <td class="tdStyle gesture" v-for="(item1, index1) in item['name']" :key="index1"
                @click="getYg(index, index1, item1, item['date'])" :class="{
                  notClick: !item['date'].includes(pageData.checkHeadList[index1]),
                }">{{ item1['name' + index1] }}
              </td>
            </tr>
          </tbody>
        </table>
        <span style="color: red">*灰色格子为此工单没有此天数</span>
      </div>
      <template #footer>
        <a-button type="primary" size="small" @click="handleBeforeOk" v-if="permissionStore.hasPermisson('zjpg.bc')">保存
        </a-button>
      </template>
    </a-modal>
    <a-modal v-model:visible="visible1" title="指派值机人" @cancel="handleCancel1" :draggable="true" style="z-index: 1000">
      <a-form :model="pageData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <!-- <a-form-item label="公司/部门/组" field="firmId">
          <a-cascader
            class="bacClass"
            v-model="pageData.firmId"
            :options="pageData.firmList"
            @focus="getFirmGroup"
            @change="changeFrim"
            :value-key="pageData.firmId"
            allow-clear
            style="z-index: 1200"
             
          />
        </a-form-item> -->
        <CorporateSectorCascader ref="cascaderRef" :configCascader="configCascader" @changeCascader="changeCascader" />
        <a-form-item field="ygName" label="员工">
          <a-select popup-container="html"  class="bacClass" v-model="pageData.ygName" @focus="getYgName" :loading="loading6"
            @search="handleSearch6" :filter-option="false" style="z-index: 1200" allow-search allow-clear>
            <a-option v-for="(item, index) in pageData.ygNameList" :key="index" :value="item['id']">
              {{ item['name'] }}
            </a-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item field="ygType" label="员工岗位">
                                <a-select popup-container="html"  class="bacClass" v-model="pageData.ygType" @focus="getYgType" :disabled="pageData.isShow"
                                    @change="changeType">
                                    <a-option v-for="(item, index) in pageData.ygTypeList" :key="index" :value="item['id']">
                                        {{ item["post"] }}</a-option>
                                </a-select>
                            </a-form-item>
                            <a-form-item field="ygName" label="员工名称">
                                <a-select popup-container="html"  class="bacClass" v-model="pageData.ygName" @focus="getYgName" :disabled="pageData.isShow1">
                                    <a-option v-for="(item, index) in pageData.ygNameList" :key="index" :value="item['id']">
                                        {{ item["name"] }}</a-option>
                                </a-select>
                            </a-form-item> -->
      </a-form>
      <template #footer>
        <a-button type="primary" size="small" @click="handleOk">保存</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import { ref, reactive, onMounted, onActivated, getCurrentInstance } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import emitter from '@/hooks/useEventBus'
import validate from '@/hooks/useValidate'
import { DatasetComponent } from 'echarts/components'
import { AnyARecord } from 'dns'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import { url } from 'inspector'
import usePermission from '@/store/modules/permission'

import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { Post } from '@/api/basedata'
import { slicing } from '@/utils/caseFrimAndSecRig'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
interface ClothInfo {
  id: any
  dutymachineCode: string | undefined
  machineCode: string | undefined
  weaveCode: string | undefined
  planOrderCode: string | undefined
  greyCode: string | undefined
  grayName: string | undefined
  customName: string | undefined
  storey: string | undefined
  employeeId: string | undefined
  employeeName: string | undefined
  dutymachineDate: string | undefined
  schedulStartDate: string | undefined
  schedulEndDate: string | undefined
  dutymachineStartDate: string | undefined
  dutymachineEndDate: string | undefined
  dutymachineState: number | undefined
  dispatchState: number | undefined
  monitorState: number | undefined
  monitor: string | undefined
  obsoleteState: number | undefined
  deleteState: number | undefined
  remark: string | undefined
  createName: string | undefined
  createTime: string | undefined
  updateName: string | undefined
  updateTime: string | undefined
}

export default {
  name: 'CheckDispatch2',
  setup() {
    const { proxy } = getCurrentInstance()
    const tabValue = ref<any>(proxy.$route.query.name)
    console.log(tabValue.value)
    const pageData1 = reactive<any>({
      tableIndex: tabValue || '1',
    })
    let cascaderRef = ref('')
    let configCascader = ref<{}>({
      corporateWidth: '400px', //公司宽度
      sectorWidth: '400px', //部门宽度
      corporateRquired: false, //公司是否必填
      sectorRquired: false, //部门是否必填
      size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
      corporateName: '公司', //公司label
      sectorName: '部门', //部门label
    })
    const changeCascader = (data: any) => {
      pageData.ygName = ''
      pageData.ygNameList = []
      const { corporateId, sectorId } = data
      console.log(corporateId)
      pageData.firmId = corporateId
      pageData.applyBranchId = sectorId
    }
    const headerShow = ref<boolean>(true)
    function PageSize(val: any) {
      if (tableId.value == 1) {
        pagination.page = val
        doRefresh()
      } else if (tableId.value == 2) {
        paginations.page = val
        doRefresh2()
      }
    }

    function change1(val: any) {
      if (tableId.value == 1) {
        pagination.pageSize = val
        doRefresh()
      } else if (tableId.value == 2) {
        paginations.pageSize = val
        doRefresh2()
      }
    }
    //查询 未值机
    function doRefresh() {
      pageData.pageLoading = true
      post({
        url: '/planSingle/dutymachine/getPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: 0,
          dutymachineState: pageData.dutymachineState,
          dutymachineCode: pageData.dutymachineCode,
          greyCode: dataForm.greyCode,
          grayName: dataForm.grayName,
          planOrderCode: dataForm.planOrderCode,
          weaveCode: dataForm.weaveCode,
          storey: dataForm.storey,
          dateStart: pageData.dateStart,
          dateEnd: pageData.dateEnd,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)
            gridOption.value.setRowData(data.list)
            pagination.setTotalSize(data.total)
            console.log(data.total)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    //查询 已值机
    function doRefresh2() {
      pageData.pageLoading = true
      post({
        url: '/planSingle/dutymachine/getPage',
        data: {
          page: paginations.page,
          size: paginations.pageSize,
          deleteState: 0,
          dutymachineState: pageData.dutymachineState,
          dutymachineCode: pageData.dutymachineCode,
          greyCode: dataForm.greyCode,
          grayName: dataForm.grayName,
          planOrderCode: dataForm.planOrderCode,
          weaveCode: dataForm.weaveCode,
          storey: dataForm.storey,
          dateStart: pageData.dateStart,
          dateEnd: pageData.dateEnd,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            paginations.setTotalSize(data.total)
            table.handleSuccess(data.list)
            gridOption2.value.setRowData(data.list)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const selectedRowKeysChecked = useRowSelection()
    const pagination = usePagination(doRefresh)
    const paginations = usePagination(doRefresh2)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '工单号',
        key: 'dutymachineCode',
        dataIndex: 'dutymachineCode',
        width: 150,
      },
      {
        title: '机台号',
        key: 'machineCode',
        dataIndex: 'machineCode',
        width: 150,
      },
      {
        title: '生产单号',
        key: 'weaveCode',
        dataIndex: 'weaveCode',
        width: 150,
      },
      {
        title: '织布单号',
        key: 'planOrderCode',
        dataIndex: 'planOrderCode',
        width: 150,
      },
      {
        title: '坯布编号',
        key: 'greyCode',
        dataIndex: 'greyCode',
        width: 150,
      },

      {
        title: '坯布名称',
        key: 'grayName',
        dataIndex: 'grayName',
        width: 150,
      },

      {
        title: '客户名称',
        key: 'customName',
        dataIndex: 'customName',
        width: 150,
      },

      {
        title: '楼层',
        key: 'storey',
        dataIndex: 'storey',
        width: 150,
      },

      {
        title: '日期',
        key: 'schedulDate',
        dataIndex: 'schedulDate',
        width: 200,
      },
    ])
    let tc1: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
      }
      return obj
    })
    let a1 = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc1 = a1.concat(tc1)
    const tableColumnsChecked = useTableColumn([
      {
        title: '工单号',
        key: 'dutymachineCode',
        dataIndex: 'dutymachineCode',
        width: 150,
      },
      {
        title: '机台号',
        key: 'machineCode',
        dataIndex: 'machineCode',
        width: 150,
      },

      {
        title: '生产单号',
        key: 'weaveCode',
        dataIndex: 'weaveCode',
        width: 150,
      },

      {
        title: '织布单号',
        key: 'planOrderCode',
        dataIndex: 'planOrderCode',
        width: 150,
      },

      {
        title: '坯布编号',
        key: 'greyCode',
        dataIndex: 'greyCode',
        width: 150,
      },

      {
        title: '坯布名称',
        key: 'grayName',
        dataIndex: 'grayName',
        width: 150,
      },

      {
        title: '班长确认',
        key: 'monitor',
        dataIndex: 'monitor',
        width: 150,
      },
      {
        title: '客户名称',
        key: 'customName',
        dataIndex: 'customName',
        width: 150,
      },
      {
        title: '楼层',
        key: 'storey',
        dataIndex: 'storey',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      {
        title: '日期',
        key: 'dutymachineDate',
        dataIndex: 'dutymachineDate',
        width: 150,
      },
      {
        title: '操作',
        key: 'id',
        dataIndex: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right',
      },
    ])

    let tc2: any[] = tableColumnsChecked.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
      }
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 165
        obj['lockPosition'] = 'right'
        obj['cellRenderer'] = {
          template: `<a-space><el-button style="color:#165dff;" link @click="a"  v-if="e&&c!=1" >班长确认</el-button>
            <el-button type="info" link disabled  v-if="e&&c==1">班长确认</el-button>
            <el-button style="color:#165dff;" link  @click="b">明细</el-button></a-space>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data, 1)
            }
            const b = () => {
              editHandler(props.params.data, 2)
            }
            return {
              e: permissionStore.hasPermisson('zjpg.bzqd'),
              c:props.params.data.monitorState,
              a,
              b
            }
          },
        }
      }

      return obj
    })

    let a2 = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc2 = a2.concat(tc2)

    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dutymachineCode: any
      greyCode: any
      grayName: any
      planOrderCode: any
      weaveCode: any
      storey: any
      dutymachineDate: any[]
      dutymachineDate1: any[]
      pageLoading: boolean
      rHeight: any
      dutymachineState: number | undefined
      checkHeadList: any[]
      checkBodyList: any[]
      bodyValueList: any[]
      dataList: any[]
      machineCodeOb: {}
      getList: any[]
      dropDownList: any[]
      tcDutymachineCode: any
      tcStorey: any
      tcDutymachineCodeList: any[]
      tcStoreyList: any[]
      ygType: any
      ygName: any
      ygTypeList: any[]
      ygNameList: any[]
      firmList: any[]
      firmId: any
      isShow: boolean
      isShow1: boolean
      filterList: any[]
      editYgTime: any[]
      employeeId: any
      employeeName: string | undefined
      NowDate: any
      dutymachineId: any
      dateStart: any
      dateEnd: any
      applyBranchId: any
      isDetails: boolean
    }>({
      showAdd: false,
      sideTitle: '新增值机派工',
      dutymachineCode: '',
      greyCode: '',
      grayName: '',
      planOrderCode: '',
      weaveCode: '',
      storey: '',
      dutymachineDate: [],
      dutymachineDate1: [],
      pageLoading: false,
      rHeight: '',
      dutymachineState: 0,
      checkHeadList: [],
      checkBodyList: [],
      bodyValueList: [],
      dataList: [],
      machineCodeOb: {},
      getList: [],
      dropDownList: [],
      tcDutymachineCode: '',
      tcStorey: '',
      tcDutymachineCodeList: [],
      tcStoreyList: [],
      ygType: '',
      ygName: '',
      ygTypeList: [],
      ygNameList: [],
      firmList: [],
      firmId: null,
      isShow: true,
      isShow1: true,
      filterList: [],
      editYgTime: [],
      employeeId: null,
      employeeName: '',
      NowDate: '',
      dutymachineId: null,
      dateStart: '',
      dateEnd: '',
      applyBranchId: '',
      isDetails: false
    })
    //下拉框得到焦点
    const focusSel = (val: any) => {
      selCxAll(val)
    }

    //下拉数据
    const options = ref<any>(pageData.dropDownList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = { dutymachineCode: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.dropDownList
        loading.value = false
      } else {
        options.value = []
      }
    }
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = { greyCode: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.dropDownList
        loading.value = false
      } else {
        options.value = []
      }
    }
    const handleSearch2 = (value: any) => {
      if (value) {
        const ob = { grayName: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.dropDownList
        loading.value = false
      } else {
        options.value = []
      }
    }
    const handleSearch3 = (value: any) => {
      if (value) {
        const ob = { planOrderCode: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.dropDownList
        loading.value = false
      } else {
        options.value = []
      }
    }
    const handleSearch4 = (value: any) => {
      if (value) {
        const ob = { weaveCode: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.dropDownList
        loading.value = false
      } else {
        options.value = []
      }
    }
    const handleSearch5 = (value: any) => {
      if (value) {
        const ob = { storey: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.dropDownList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      if (tableId.value == 1) {
        val['dutymachineState'] = 0
      } else {
        val['dutymachineState'] = 1
      }
      post({
        url: 'planSingle/dutymachine/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.dropDownList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      if (tableId.value == 1) {
        pagination.page = 1
        pageData.dutymachineState = 0
        doRefresh()
      } else {
        paginations.page = 1
        pageData.dutymachineState = 1
        doRefresh2()
      }
    })
    //查询
    const selectHandler = () => {
      loadings.value = true
      if (tableId.value == 1) {
        pagination.page = 1
        doRefresh()
      } else if (tableId.value == 2) {
        paginations.page = 1
        doRefresh2()
      }
    }

    let loadings = ref(false)
    const dataForm = reactive<ClothInfo>({
      id: null,
      dutymachineCode: '',
      machineCode: '',
      weaveCode: '',
      planOrderCode: '',
      greyCode: '',
      grayName: '',
      customName: '',
      storey: '',
      employeeId: '',
      employeeName: '',
      dutymachineDate: '',
      schedulStartDate: '',
      schedulEndDate: '',
      dutymachineStartDate: '',
      dutymachineEndDate: '',
      dutymachineState: 0,
      dispatchState: 0,
      monitorState: 0,
      monitor: '',
      obsoleteState: 0,
      deleteState: 0,
      remark: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
    }
    // 表格准备事件
    const gridOption2 = ref()
    const gridReady2 = (params: any) => {
      gridOption2.value = params.api
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      pageData.showAdd = false
      formRef.value?.validate().then((err) => {
        if (!err) {
          pageData.editYgTime.forEach(function (o) {
            if (
              o['dutymachineStartDate'] == null ||
              o['dutymachineStartDate'] == undefined ||
              o['dutymachineStartDate'] == ''
            ) {
              o['dutymachineStartDate'] = pageData.NowDate
            }
            if (
              o['dutymachineEndDate'] == null ||
              o['dutymachineEndDate'] == undefined ||
              o['dutymachineEndDate'] == ''
            ) {
              o['dutymachineEndDate'] = pageData.NowDate
            }
          })
          post({
            url: 'planSingle/dutymachine/monitorConfirm',
            data: {
              dutymachineId: pageData.dutymachineId,
              userList: pageData.editYgTime,
            },
          }).then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields()
              pageData.showAdd = false
              Message.success({
                content: '班长确认成功',
                duration: 5000,
              })
              doRefresh2()
            } else {
              Message.error({
                content: res.message,
                duration: 5000,
              })
            }
          })
        }
      })
    }

    //班长确认
    const editHandler = (record: ClothInfo, num: any) => {
      loadings.value = true
      var day2 = new Date()
      pageData.NowDate = day2.getFullYear() + '-' + (day2.getMonth() + 1) + '-' + day2.getDate()
      dataForm.id = record.id
      post({
        url: 'planSingle/dutymachineDispatch/getDutymachineDispatchById',
        data: { dutymachineId: record.id },
      }).then(({ code, data, message }: any) => {
        if (code === 200) {
          if (data.length == 0) {
            Message.warning({
              content: '暂无数据',
              duration: 5000,
            })
            //  doRefresh2()
          } else {
            pageData.editYgTime = data
            pageData.sideTitle = '修改值机派工'
            pageData.showAdd = true
            pageData.dutymachineId = record.id
            if (num == 2) {
              pageData.isDetails = true
              pageData.sideTitle = '明细'
            }
          }
        } else {
          Message.error({
            content: message,
            duration: 5000,
          })
        }
      })
    }

    //值机派工弹窗
    const visible = ref(false)
    const handleClick = () => {
      pageData.checkBodyList = []
      pageData.checkHeadList = []
      pageData.getList = []
      pageData.bodyValueList = []
      if (gridOption.value.getSelectedRows().length > 0) {
        visible.value = true
        post({
          url: 'planSingle/dutymachine/getListByIds',
          // data: selectedRowKeys.value,
          data: gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          }),
        }).then(({ code, data, message }: any) => {
          if (code === 200) {
            pageData.getList = data
            pageData.filterList = pageData.getList.filter(function (o) {
              return gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .includes(o['id'])
              // return selectedRowKeys.value.includes(o["id"])
            })
            if (pageData.filterList.length > 0) {
              pageData.filterList.forEach(function (o) {
                //筛选工单号和楼层
                if (!pageData.tcDutymachineCodeList.includes(o['dutymachineCode'])) {
                  pageData.tcDutymachineCodeList.push(o['dutymachineCode'])
                }
                if (!pageData.tcStoreyList.includes(o['storey'])) {
                  pageData.tcStoreyList.push(o['storey'])
                }
              })
              cxTable()
            }
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
      } else {
        Message.warning({
          content: '请先勾选数据',
          duration: 5000,
        })
      }
      param = []
    }
    // 渲染table的数据
    const cxTable = () => {
      // handleClick()
      pageData.checkBodyList = []
      pageData.checkHeadList = []
      pageData.getList = []
      pageData.bodyValueList = []
      // if (pageData.tcDutymachineCode !== '' && pageData.tcStorey !== '') {
      // pageData.filterList = pageData.filterList.filter(function (o) {
      //     var bool = true;
      //     if (pageData.tcDutymachineCode != '' && bool) {
      //         if (o["dutymachineCode"] != pageData.tcDutymachineCode) {
      //             bool = false;
      //         }
      //     }
      //     if (pageData.tcStorey !== '' && bool) {
      //         if (o["storey"] != pageData.tcStorey) {
      //             bool = false;
      //         }
      //     }
      //     return bool;
      // })

      //拼凑表格数据
      pageData.machineCodeOb = []
      pageData.filterList.forEach(function (o) {
        if (!pageData.checkHeadList.includes(o['schedulDate'])) {
          pageData.checkHeadList.push(o['schedulDate'])
        }
        if (pageData.machineCodeOb[o['machineCode']] == undefined) {
          pageData.machineCodeOb[o['machineCode']] = []
          pageData.machineCodeOb[o['machineCode']].push(o['schedulDate'])
        } else {
          pageData.machineCodeOb[o['machineCode']].push(o['schedulDate'])
        }
      })
      for (var key in pageData.machineCodeOb) {
        var ob = {}
        ob['machineName'] = key
        ob['shift'] = '白班'
        ob['date'] = pageData.machineCodeOb[key]
        var bLis: any = []
        var wLis: any = []
        for (let i = 0; i < pageData.checkHeadList.length; i++) {
          var bob = {}
          bob['name' + i] = ''
          //构造渲染行和列的数据
          bLis.push(bob)
          var wob = {}
          wob['name' + i] = ''
          wLis.push(wob)
        }
        ob['name'] = bLis
        pageData.checkBodyList.push(ob)
        var wOb = {
          machineName: '',
          shift: '晚班',
          date: pageData.machineCodeOb[key],
          name: wLis,
        }
        pageData.checkBodyList.push(wOb)
      }

      //日期排序
      pageData.checkHeadList.sort((a, b) => a.localeCompare(b))

      // for (let i = 0; i < pageData.checkHeadList.length; i++) {
      //     var bob = {};
      //     bob["name" + i] = ""
      //     //构造渲染行和列的数据
      //     bLis.push(bob)
      //     var wob = {};
      //     wob["name" + i] = ""
      //     wLis.push(wob)

      // }
      // pageData.checkBodyList.forEach(function (o) {
      //     if (o["shift"] == '白班') {
      //         o["name"] = bLis
      //     } else {
      //         o["name"] = wLis
      //     }

      // })
    }
    //第一个弹窗的确定
    const handleBeforeOk = () => {
      if (param.length <= 0) {
        Message.warning({
          content: '请先分配人员',
          duration: 2000,
        })
        return
      }
      param.forEach(function (o: any) {
        o['bai']['employeeId'] = parseFloat(o['bai']['employeeId'])
      })
      pageData.pageLoading = true
      post({
        url: 'planSingle/dutymachine/dispatch',
        data: param,
      })
        .then(({ code, data, message }: any) => {
          if (code === 200) {
            Message.success({
              content: '分配成功',
              duration: 5000,
            })
            visible.value = false
            selectHandler()
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    const handleCancel = () => {
      visible.value = false
    }
    // let tableId = 1
    let tableId: any = ref(1);
    //已值机 未值机tab切换
    const changeTabs = (key: any) => {
      tableId.value = key
      if (key == 1) {
        pagination.page = 1
        pageData.dutymachineState = 0
        doRefresh()
      } else {
        paginations.page = 1
        pageData.dutymachineState = 1
        doRefresh2()
      }
    }
    //弹出员工框
    const visible1 = ref(false)
    let sy = 0
    let sy1 = 0
    let tdob = ''
    let dutymachineId: any = null
    let machineNameTemp: any = null
    //行内点击事件选择员工
    const getYg = (index: any, index1: any, key: any, dateList: any) => {
      dutymachineId = null
      machineNameTemp = null
      //拿到此单元格表头的日期
      let headDate = pageData.checkHeadList[index1]
      if (dateList.includes(headDate)) {
        sy = index
        sy1 = index1
        for (const k in key) {
          tdob = k
        }
        //拿到行数据id
        var machineName = pageData.checkBodyList[index]['machineName']
        machineNameTemp = machineName
        if (machineName == '') {
          machineName = pageData.checkBodyList[index - 1]['machineName']
        }
        let lisId = pageData.filterList.filter(function (o) {
          return o['machineCode'] == machineName && o['schedulDate'] == headDate
        })
        if (lisId.length > 0) {
          dutymachineId = lisId[0]['id']
        }
        pageData.firmList = []
        pageData.ygTypeList = []
        pageData.ygNameList = []
        pageData.firmId = null
        pageData.ygType = null
        pageData.ygName = null
        pageData.ygTypeList = []
        pageData.ygNameList = []
        visible1.value = true
        pageData.isShow = true
        pageData.isShow1 = true
        cascaderRef.value.resetForm()
        pageData.ygName = ''
        pageData.ygNameList = []
        pageData.firmId = ''
        pageData.applyBranchId = ''
      } else {
        visible1.value = false
      }
    }
    const handleCancel1 = () => {
      visible1.value = false
    }
    let param: any = []
    const handleOk = () => {
      if (
        pageData.firmId == '' ||
        pageData.firmId == null ||
        pageData.ygName == '' ||
        pageData.ygName == null
      ) {
        Message.error({
          content: '请选择完整公司和员工名称',
          duration: 5000,
        })
      } else {
        var editLis = pageData.ygNameList.filter(function (o) {
          return o['id'] == pageData.ygName
        })
        pageData.checkBodyList[sy]['name'][sy1][tdob] = editLis[0]['name']
        var count = 0
        for (let i = 0; i < param.length; i++) {
          let ob = param[i]
          if (ob.dutymachineId == dutymachineId) {
            if (machineNameTemp != null) {
              if (machineNameTemp == '') {
                ob['wan'] = {
                  employeeName: editLis[0]['name'],
                  employeeId: editLis[0]['id'],
                  employeeCode: editLis[0]['code'],
                }
              } else {
                ob['bai'] = {
                  employeeName: editLis[0]['name'],
                  employeeId: editLis[0]['id'],
                  employeeCode: editLis[0]['code'],
                }
              }
            }
            count++
          }
        }
        if (count == 0) {
          let ob: any = {}
          ob.dutymachineId = dutymachineId
          if (machineNameTemp != null) {
            if (machineNameTemp == '') {
              ob['wan'] = {
                employeeName: editLis[0]['name'],
                employeeId: editLis[0]['id'],
                employeeCode: editLis[0]['code'],
              }
            } else {
              ob['bai'] = {
                employeeName: editLis[0]['name'],
                employeeId: editLis[0]['id'],
                employeeCode: editLis[0]['code'],
              }
            }
          }
          param.push(ob)
        }
        visible1.value = false
      }
    }
    //获取公司信息
    const getFirmList = () => {
      post({
        url: 'org/baCompany/getTreeCompanyByUser',
      }).then((res) => {
        if (res.code == 200) {
          pageData.firmList = res.data
          pageData.ygTypeList = []
          pageData.ygNameList = []
        } else {
          Message.error({
            content: '获取公司信息失败',
            duration: 5000,
          })
        }
      })
    }
    //获取员工岗位
    const getYgType = () => {
      post({
        url: '/hr/post/getAllActivePost',
        data: { id: pageData.firmId },
      }).then((res) => {
        if (res.code == 200) {
          pageData.ygTypeList = JSON.parse(res.data)
          pageData.ygNameList = []
        } else {
          Message.error({
            content: '查询员工岗位失败',
            duration: 5000,
          })
        }
      })
    }
    //获取员工名称
    const getYgName = () => {
      // post({
      //     url: '/hr/employee/getWorkingEmployeeListByCompanyIdAndPostId',
      //     data: {
      //         companyId: pageData.firmId,
      //         postId: pageData.ygType
      //     },
      // }).then(res => {
      //     if (res.code == 200) {
      //         pageData.ygNameList = JSON.parse(res.data)
      //     } else {
      //         Message.error({
      //             content: "查询员工名称失败",
      //             duration: 5000,
      //         });
      //     }
      // })
      getAllNickname('')
    }
    const options6 = ref(pageData.ygNameList)
    const loading6 = ref(false)

    const handleSearch6 = (value: any) => {
      if (value) {
        loading6.value = true
        getAllNickname(value)
        loading6.value = false
      } else {
        options.value = []
      }
    }

    //查所有的员工
    function getAllNickname(val: any) {
      post({
        url: 'org/hrEmployee/getList',
        data: {
          company_id: pageData.firmId,
          department_id: pageData.applyBranchId,
          obsoleteState: 0,
          deleteState: 0,
        },
      }).then((res) => {
        if (res.code == 200) {
          pageData.ygNameList = res.data
        } else {
          Message.error({
            content: '查询员工名称失败',
            duration: 5000,
          })
        }
      })
    }

    //公司下拉框改变 员工岗位可选
    const changeFrim = () => {
      pageData.isShow = false
    }
    const changeType = () => {
      pageData.isShow1 = false
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()
    //获取公司部门组列表
    const getFirmGroup = () => {
      post({
        url: 'org/baCompany/getTreeCompanyByUser',
      }).then(({ code, data }) => {
        if (code === 200) {
          pageData.firmList = data
        }
      })
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }
    const pagingList1: any = ref(pagingList)
    return {
      tableId,
      pagingList1,
      huiche,
      localeText1,
      paginations,
      defaultColDef,
      tc1,
      tc2,
      gridOption,
      gridOption2,
      gridReady,
      gridReady2,
      sideOk,
      formRef,
      dataForm,
      selectedRowKeys,
      s: selectedRowKeysChecked.selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      pageData1,
      editHandler,
      selectHandler,
      tableColumnsChecked,
      changeTabs,
      handleClick,
      handleCancel,
      visible,
      handleBeforeOk,
      options,
      loading,
      options6,
      loading6,
      handleSearch,
      handleSearch1,
      handleSearch2,
      handleSearch3,
      handleSearch4,
      handleSearch5,
      handleSearch6,
      focusSel,
      headerShow,
      getYg,
      visible1,
      handleCancel1,
      handleOk,
      getYgType,
      getYgName,
      getFirmList,
      changeFrim,
      changeType,
      cxTable,
      permissionStore,
      configCascader,
      changeCascader,
      getFirmGroup,
      change1,
      PageSize,
      cascaderRef,
    }
  },
  components: { Toolbar, PageTabelLayout, CorporateSectorCascader },
}
</script>
<style scoped >
#Table td,
#Table th {
  border: 1px solid #ccc;
  padding: 10px;
}

.tdStyle {
  min-width: 100px;
}

.notClick {
  background-color: gray;
  cursor: no-drop;
}

:deep(.SendCheck) {
  z-index: 100 !important;
}
</style>
